#!/usr/bin/env python
import copy
from io.GenOutput import GenOutput
class Combinator:
    
    def __init__(self):
        pass
    
    def two_point_xover(self, parent_a, parent_b, max_instances, max_distance):
        assert parent_a != None
        assert parent_b != None
        
        mod_parent_a = copy.deepcopy(parent_a)
        mod_parent_b = copy.deepcopy(parent_b)
        
        material_a = mod_parent_a.subgraph(mod_parent_a.startshape, max_instances, max_distance)
        assert material_a != None
        
        material_b = mod_parent_b.subgraph(mod_parent_b.startshape, max_instances, max_distance)
        assert material_a != None
        
        table = self.build_table(parent_a, parent_b)
        
        mod_parent_a.combine(material_b, table)
        mod_parent_a.repair_ss()
        mod_parent_b.combine(material_a, table)
        mod_parent_b.repair_ss()
        
        return (mod_parent_a, mod_parent_b)
    
    def build_table(self, parent_a, parent_b):
        half_a = parent_a.bfs(parent_a.startshape, parent_a)
        assert half_a != None
        
        half_b = parent_b.bfs(parent_b.startshape, parent_b)
        assert half_b != None
        
        loose_a = [item for item in parent_a.nodes() if not item in half_a]
        loose_b = [item for item in parent_b.nodes() if not item in half_b]
        
        half_a.extend(loose_a)
        half_b.extend(loose_b)
        
        print "HALF-A:"
        print half_a
        print "HALF-B:"
        print half_b
        
        table = {}
        
        for el1, el2 in zip(half_a, half_b):
            table[el1] = el2
        
        return table
